package com.example.bigevent.config;

import cn.hutool.core.io.CharsetDetector;
import org.mozilla.universalchardet.UniversalDetector;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Objects;

public class EncodeTest1 {
    public static Charset getCharset(File file) {
        try (InputStream in = new FileInputStream(file);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            //最多循环3次,每次2kb,主要是防止一次不能获取到编码
            int cycleNum = 0;
            Charset charset = null;
            byte[] buffer = new byte[4096];
            int len;
            while (cycleNum < 3 && (len = in.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
                baos.flush();
                cycleNum++;
                charset = CharsetDetector.detect(1024 * cycleNum, new ByteArrayInputStream(baos.toByteArray()), null);
                if (Objects.nonNull(charset)) {
                    break;
                }
            }
            if (charset != null) {
            } else {
                return Charset.defaultCharset();
            }
            return charset;
        } catch (Exception e) {
            //使用默认编码utf-8
            return Charset.defaultCharset();
        }
    }

    public static void main(String[] args) {
        String filePath = "D:\\testencoding\\gb.txt";
        String bv = "D:\\testencoding\\b.txt";
        String java1 = "D:\\testencoding\\GlobalExceptionHandler.java";

        File file = new File(filePath);
        String ecoding = getCharset(file).name();
        System.err.println(ecoding);

        try (InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath), ecoding);
             BufferedReader reader = new BufferedReader(inputStreamReader)) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
